package risk.control.project.framework.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import risk.control.project.framework.base.BaseEncryption;
import risk.control.project.utils.TimeUtils;

import java.util.HashMap;

/**
 * 校验请求时间戳合法性
 */
@Service
public class TimestampService extends BaseEncryption {

    private static final Logger logger = LoggerFactory.getLogger(TimestampService.class);

    /**
     * 校验时间戳
     *
     * @param realBody realBody
     * @return resMap
     */
    public HashMap<String, String> verifierTimestamp(String realBody) {
        HashMap<String, String> resMap = new HashMap<>();
        if (realBody == null || realBody.isEmpty()) {
            resMap.put("state", "001");
            resMap.put("msg", "body为空");
            return resMap;
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(realBody);
        if (!jsonObject.containsKey("timestamp")) {
            resMap.put("state", "003");
            resMap.put("msg", "时间戳为空");
            return resMap;
        }
        String timestamp = jsonObject.getString("timestamp");
        //验证时间戳（前后不超过1分钟）
        long timeDifference = TimeUtils.calculate(Long.parseLong(timestamp), System.currentTimeMillis());
        long limit = 1000 * 60;
        if (Math.abs(timeDifference) > limit) {
            //时间戳超时了
            resMap.put("state", "002");
            resMap.put("msg", "该请求已失效");
            return resMap;
        }
        resMap.put("state", "000");
        resMap.put("msg", "时间戳验证通过");
        return resMap;
    }
}
